import logging

from goods_info.models import GoodsModel, GoodsInventoryModel
from .models import WarehouseModel
from django.db.models.signals import post_save
from django.dispatch import receiver

logger = logging.getLogger('erp')

methods = {'POST': '新增', 'GET': '查询', 'PUT': '修改', 'DELETE': '删除', 'PATCH': '局部修改'}


@receiver(post_save, sender=WarehouseModel)
def create_goods_inventory(sender, instance, created, **kwargs):
    '''
    创建信号监控函数
    创建新仓库之后， 给所有的货品在当前的新仓库 新增库存数据
    '''
    if created:
        logger.info('创建当前新仓库的所有库存数据--每一个商品都要对应的库存记录')
        if isinstance(instance, WarehouseModel):
            # 查询所有的货品id
            ids = GoodsModel.objects.values_list('id', flat=True).all()
            # 批量插入库存记录数据
            inventory_list = []
            for goods_id in ids:
                inventory_list.append(
                    GoodsInventoryModel(goods_id=goods_id,
                                        warehouse_id=instance.id,
                                        warehouse_name=instance.name)
                )
            # 批量新增的函数
            GoodsInventoryModel.objects.bulk_create(inventory_list)

        else:
            logger.info('不是WarehouseModel类型，所以不需要创建库存数据')
